#include<iostream>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "log.hpp"
#include "lockguard.hpp"



int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cerr << "Usage: " << argv[0] << " server-ip server-port" << std::endl;
        exit(0);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    //1.创建sockfd

    int sockfd = socket(AF_INET,SOCK_STREAM,0);
    if(sockfd<0)
	{
	LOG(FATAL,"client socket create err\n");
		exit(4);
	};
    //2.链接服务器（与此同时，系统会自动bind sockfd和自己的IP和系统随机生成的端口号）
    struct sockaddr_in server;
    server.sin_family= AF_INET;
    server.sin_port =htons(serverport);
    inet_pton(AF_INET,serverip.c_str(),&server.sin_addr.s_addr);
    if(connect(sockfd,(struct sockaddr*)&server,sizeof(server))<0)
    {
	    LOG(FATAL,"client connect  err\n");
                exit(5);
    };
    //3.实现业务(目前为最基础的，write和read)
    while(true)
    {
	    	std::cout<<"Please Enter#";
		std::string message;
		std::getline(std::cin,message);
		write(sockfd,message.c_str(),message.size());
		char echo_buffer[1024];
       int n = read(sockfd, echo_buffer, sizeof(echo_buffer));
        if(n > 0)
        {
            echo_buffer[n] = 0;
            std::cout << echo_buffer << std::endl;
        }
        else
        {
            break;
        }

    };
	close(sockfd);
	return 0;

};
